SPB Git

Repository Public

page.tsx 14.0 KB 282 lines tsx

1/**2 * =============================================================================3 *                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : SPB Private Cloud8 * File             : app/dashboard/shared-space/[id]/page.tsx9 * Module           : app10 * Repository       : https://git.spboucher.ai/spb-cloud11 * Project Website  : https://cloud.spboucher.ai12 * Created          : 2026-02-2113 * Last Modified    : 2026-09-0714 *15 * Author           : Simon-Pierre Boucher16 * Position         : Professor of Finance17 * Institution      : Université du Québec en Outaouais (UQO)18 * Organization     : SP Boucher19 * Website          : https://spboucher.ai20 * Git              : https://git.spboucher.ai21 *22 * Preferred Contact: admin@spboucher.ai23 * Technical Contact: dev@spboucher.ai24 * Security/Admin   : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License          : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142"use client";4344import { useState, useEffect, useCallback, useRef } from "react";45import { useParams } from "next/navigation";46import AppShell from "@/components/layout/AppShell";47import FolderCard from "@/components/folders/FolderCard";48import FileCard from "@/components/files/FileCard";49import FileUpload, { type FileUploadHandle } from "@/components/files/FileUpload";50import PreviewEngine from "@/components/preview/PreviewEngine";51import Button from "@/components/ui/Button";52import SharedBadge from "@/components/ui/SharedBadge";53import Modal from "@/components/ui/Modal";54import PageHeader, { EmptyState } from "@/components/ui/PageHeader";55import { useShellHeader } from "@/components/layout/ShellContext";56import { formatFileSize } from "@/lib/utils";57import { notifyFoldersChanged } from "@/components/files/dnd";58import type { FileData } from "@/types/files";59import { LayoutGrid, List, Upload, FolderPlus, Users, ChevronRight, Home } from "lucide-react";60import { motion, AnimatePresence } from "framer-motion";61import toast from "react-hot-toast";6263interface SpaceData {64  id: string;65  name: string;66  quotaBytes: number;67  usedBytes: number;68  members: { id: string; user: { id: string; name: string | null; username: string | null } }[];69  folders: { id: string; name: string; parentId: string | null }[];70}7172interface FolderData {73  id: string;74  name: string;75  parentId: string | null;76  sharedSpaceId?: string | null;77  _count?: { files: number; children: number };78  createdAt: string;79}8081export default function SharedSpacePage() {82  const params = useParams();83  const id = params.id as string;8485  const [space, setSpace] = useState<SpaceData | null>(null);86  const [folders, setFolders] = useState<FolderData[]>([]);87  const [files, setFiles] = useState<FileData[]>([]);88  const [path, setPath] = useState<{ id: string; name: string }[]>([]);89  const [viewMode, setViewMode] = useState<"grid" | "list">("grid");90  const [showUpload, setShowUpload] = useState(false);91  const [showCreateFolder, setShowCreateFolder] = useState(false);92  const [newFolderName, setNewFolderName] = useState("");93  const [previewFile, setPreviewFile] = useState<FileData | null>(null);94  const [loading, setLoading] = useState(true);95  const uploadRef = useRef<FileUploadHandle>(null);9697  const currentFolderId = path[path.length - 1]?.id ?? null;9899  useShellHeader({ title: space?.name ? `Espace · ${space.name}` : "Espace partagé" });100101  const fetchData = useCallback(async () => {102    setLoading(true);103    try {104      const [spaceRes, foldersRes, filesRes] = await Promise.all([105        fetch(`/api/shared-spaces/${id}`),106        fetch(`/api/folders?sharedSpaceId=${id}&parentId=${currentFolderId || "root"}`),107        currentFolderId ? fetch(`/api/files?folderId=${currentFolderId}`) : Promise.resolve(null),108      ]);109      if (spaceRes.ok) setSpace(await spaceRes.json());110      if (foldersRes.ok) setFolders(await foldersRes.json());111      if (filesRes?.ok) {112        const filesData = await filesRes.json();113        setFiles(Array.isArray(filesData) ? filesData : filesData.files || []);114      } else setFiles([]);115    } catch {116      // ignore117    } finally {118      setLoading(false);119    }120  }, [id, currentFolderId]);121122  useEffect(() => { fetchData(); }, [fetchData]);123124  const handleCreateFolder = async () => {125    if (!newFolderName.trim()) return;126    const res = await fetch("/api/folders", {127      method: "POST",128      headers: { "Content-Type": "application/json" },129      body: JSON.stringify({ name: newFolderName.trim(), sharedSpaceId: id, parentId: currentFolderId || null }),130    });131    if (res.ok) {132      toast.success("Dossier créé");133      setShowCreateFolder(false);134      setNewFolderName("");135      notifyFoldersChanged();136      fetchData();137    } else {138      toast.error("Erreur");139    }140  };141142  const percent = space ? Math.min(Math.round((space.usedBytes / space.quotaBytes) * 100), 100) : 0;143144  return (145    <AppShell>146      <div className="flex flex-col h-full lg:flex-row overflow-x-hidden">147        <div className="flex-1 flex flex-col min-w-0 overflow-x-hidden">148          {/* En-tête de l'espace */}149          <div className="px-3 sm:px-4 lg:px-6 border-b border-line dark:border-white/[0.07]">150            <PageHeader151              compact152              icon={Users}153              tone="text-purple-600 bg-purple-500/10 dark:text-purple-300"154              title={space?.name || "Espace partagé"}155              subtitle={space ? `${space.members.length} membre${space.members.length !== 1 ? "s" : ""} · ${formatFileSize(space.usedBytes)} sur ${formatFileSize(space.quotaBytes)}` : undefined}156              actions={<SharedBadge />}157            />158            {space && (159              <div className="pb-3">160                <div className="w-full bg-gray-100 dark:bg-white/10 rounded-full h-1.5 overflow-hidden">161                  <motion.div162                    initial={{ width: 0 }}163                    animate={{ width: `${Math.max(1, percent)}%` }}164                    className={`h-full rounded-full ${percent > 90 ? "bg-rose-500" : percent > 70 ? "bg-amber-500" : "bg-purple-500"}`}165                  />166                </div>167              </div>168            )}169          </div>170171          {/* Fil d'Ariane local + outils */}172          <div className="px-3 sm:px-4 lg:px-6 py-2.5 flex items-center gap-2 border-b border-line dark:border-white/[0.07]">173            <nav className="flex-1 min-w-0 flex items-center gap-1 text-[13px] overflow-x-auto scrollbar-none whitespace-nowrap" aria-label="Fil d'Ariane">174              <button onClick={() => setPath([])} className={`flex items-center gap-1.5 px-1.5 h-8 rounded-lg transition-colors ${path.length === 0 ? "font-semibold text-gray-900 dark:text-white" : "text-gray-500 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-white/5"}`}>175                <Home className="w-4 h-4" /> Espace176              </button>177              {path.map((p, i) => (178                <span key={p.id} className="flex items-center gap-1">179                  <ChevronRight className="w-3.5 h-3.5 text-gray-300 dark:text-gray-600" />180                  <button onClick={() => setPath(path.slice(0, i + 1))} className={`px-1.5 h-8 rounded-lg truncate max-w-[10rem] transition-colors ${i === path.length - 1 ? "font-semibold text-gray-900 dark:text-white" : "text-gray-500 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-white/5"}`}>181                    {p.name}182                  </button>183                </span>184              ))}185            </nav>186            <div className="flex items-center h-10 p-1 rounded-xl bg-gray-100 dark:bg-white/[0.06] shrink-0" role="radiogroup">187              {(["list", "grid"] as const).map((v) => (188                <button key={v} role="radio" aria-checked={viewMode === v} onClick={() => setViewMode(v)} className={`relative w-9 h-8 flex items-center justify-center rounded-lg transition-colors ${viewMode === v ? "text-gray-900 dark:text-white" : "text-gray-400 hover:text-gray-700 dark:hover:text-gray-200"}`} title={v === "list" ? "Liste" : "Grille"}>189                  {viewMode === v && <motion.span layoutId="ss-view-seg" className="absolute inset-0 rounded-lg bg-surface dark:bg-white/10 shadow-card dark:shadow-none" />}190                  <span className="relative">{v === "list" ? <List className="w-4 h-4" /> : <LayoutGrid className="w-4 h-4" />}</span>191                </button>192              ))}193            </div>194            <Button variant="ghost" size="sm" onClick={() => setShowCreateFolder(true)} className="h-10 shrink-0">195              <FolderPlus className="w-4 h-4" /><span className="hidden sm:inline">Dossier</span>196            </Button>197            <Button variant="accent" size="sm" onClick={() => setShowUpload(!showUpload)} className="h-10 shrink-0" disabled={!currentFolderId} title={currentFolderId ? "Envoyer des fichiers" : "Ouvrez un dossier pour envoyer"}>198              <Upload className="w-4 h-4" /><span className="hidden sm:inline">Envoyer</span>199            </Button>200          </div>201202          {/* Upload */}203          <AnimatePresence>204            {showUpload && currentFolderId && (205              <motion.div initial={{ opacity: 0, height: 0 }} animate={{ opacity: 1, height: "auto" }} exit={{ opacity: 0, height: 0 }} className="px-3 sm:px-4 lg:px-6 pt-3 overflow-hidden">206                <FileUpload ref={uploadRef} folderId={currentFolderId} onUploadComplete={fetchData} folderName={path[path.length - 1]?.name} />207              </motion.div>208            )}209          </AnimatePresence>210211          {/* Contenu */}212          <div className="flex-1 overflow-auto px-3 sm:px-4 lg:px-6 py-4">213            {loading ? (214              <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-3">215                {Array.from({ length: 6 }).map((_, i) => <div key={i} className="h-[68px] card animate-pulse" />)}216              </div>217            ) : (218              <>219                {folders.length > 0 && (220                  <section className="mb-6">221                    <h3 className="text-[11px] font-semibold text-gray-400 uppercase tracking-wider mb-2.5">Dossiers</h3>222                    <div className={viewMode === "grid" ? "grid grid-cols-2 gap-2 sm:grid-cols-3 sm:gap-3 lg:grid-cols-4 xl:grid-cols-5" : "card overflow-clip divide-y divide-line/70 dark:divide-white/5"}>223                      {folders.map((folder) => (224                        <FolderCard key={folder.id} folder={folder} onRefresh={fetchData} viewMode={viewMode} onOpen={(f) => setPath([...path, { id: f.id, name: f.name }])} />225                      ))}226                    </div>227                  </section>228                )}229                {files.length > 0 && (230                  <section>231                    <h3 className="text-[11px] font-semibold text-gray-400 uppercase tracking-wider mb-2.5">Fichiers ({files.length})</h3>232                    <div className={viewMode === "grid" ? "grid grid-cols-2 gap-2 sm:grid-cols-3 sm:gap-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6" : "card overflow-clip divide-y divide-line/70 dark:divide-white/5"}>233                      {files.map((file) => (234                        <FileCard key={file.id} file={file} onPreview={setPreviewFile} onRefresh={fetchData} viewMode={viewMode} />235                      ))}236                    </div>237                  </section>238                )}239                {folders.length === 0 && files.length === 0 && (240                  <EmptyState241                    icon={Users}242                    title={currentFolderId ? "Dossier vide" : "Espace vide"}243                    description={currentFolderId ? "Envoyez des fichiers ou créez un sous-dossier." : "Créez un dossier pour commencer à partager."}244                    action={245                      <div className="flex items-center gap-2">246                        <Button variant="secondary" size="sm" onClick={() => setShowCreateFolder(true)}><FolderPlus className="w-4 h-4" /> Nouveau dossier</Button>247                        {currentFolderId && <Button variant="accent" size="sm" onClick={() => { setShowUpload(true); setTimeout(() => uploadRef.current?.openPicker(), 50); }}><Upload className="w-4 h-4" /> Envoyer</Button>}248                      </div>249                    }250                  />251                )}252              </>253            )}254          </div>255        </div>256257        {previewFile && (258          <div className="fixed inset-0 z-50 lg:relative lg:inset-auto lg:z-auto lg:w-[420px] xl:w-[460px] lg:shrink-0 lg:border-l lg:border-line dark:lg:border-white/[0.07]">259            <PreviewEngine file={previewFile} files={files} onClose={() => setPreviewFile(null)} onNavigate={setPreviewFile} onChanged={fetchData} />260          </div>261        )}262      </div>263264      <Modal isOpen={showCreateFolder} onClose={() => { setShowCreateFolder(false); setNewFolderName(""); }} title="Nouveau dossier" description={currentFolderId ? "Dans le dossier courant" : "À la racine de l'espace"}>265        <input266          type="text"267          placeholder="Nom du dossier"268          value={newFolderName}269          onChange={(e) => setNewFolderName(e.target.value)}270          onKeyDown={(e) => e.key === "Enter" && handleCreateFolder()}271          className="field mb-4 h-11"272          autoFocus273        />274        <div className="flex gap-2 justify-end">275          <Button variant="ghost" onClick={() => { setShowCreateFolder(false); setNewFolderName(""); }}>Annuler</Button>276          <Button variant="accent" onClick={handleCreateFolder} disabled={!newFolderName.trim()}><FolderPlus className="w-4 h-4" /> Créer</Button>277        </div>278      </Modal>279    </AppShell>280  );281}282
Files main
Menu

Theme